<?php


namespace app\v2\controller;


use app\common\controller\Checking;
use app\common\controller\Sms;
use think\Db;

class Otc extends Base
{

    /*
     * 19 otc
     */
    public function otc(){
        $data = Db::name('otc_trade')
            ->where('user_id','neq',$this->userId)
            ->where('surplus_bumber','>',0)
            ->select();
        Checking::response(200, '',$data);
    }

    /*
     * 21 买入或卖出
     * id
     * number
     */
    public function pay(){
        $params = input('param.');
        if (!Checking::keyIsExistence('id，number', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        //订单
        $trade = Db::name('otc_trade')->where('id','=',$params['id'])->find();
        //币币账户
        $asset = Db::name('users_coin')->where('user_id','=',$this->userId)->find();
        if($trade['type'] == 1){//买入类型订单，当前用户卖出
            //余额是否足够
            if($asset['usdt'] < $params['number']){
                Checking::response(-201,'可用USDT数量不足');
            }
            //修改订单剩余
            $res1 = Db::name('otc_trade')->where('id','=',$params['id'])->setDec('surplus_bumber',$params['number']);
            if(!$res1){
                Checking::response(-201,'买入失败，请重试');
            }
            //添加记录
            $data['order_num'] = $params['id'];
            $data['buy_user_id'] = $trade['user_id'];
            $data['sell_user_id'] = $this->userId;
            $data['coin_type'] = $trade['coin_type'];
            $data['number'] = $params['number'];
            $data['price'] = $trade['price'];
            $data['status'] = 2;
            $data['pay_type'] = $trade['payment'];
            $data['create_time'] = date('Y-m-d H;i:s');
            $res2 = Db::name('otc_trade_detail')->insert($data);
            if(!$res2){
                Checking::response(-201,'插入记录失败，请重试');
            }
            //短信提醒
            $phone = Db::name('users')->where('id','=',$trade['user_id'])->value('phone');
            $message = '您的OTC订单编号：'.$res2.'，请及时付款';
            $result = Sms::send($phone,$message);
            Checking::response(200,'订单已生成');
        }else{//卖出类型订单，当前用户买入
            //数量是否足够
            if($trade['surplus_bumber'] < $params['number']){
                Checking::response(-201,'超出可购买数量，购买失败');
            }
            //修改订单剩余
            $res1 = Db::name('otc_trade')->where('id','=',$params['id'])->setDec('surplus_bumber',$params['number']);
            if(!$res1){
                Checking::response(-201,'买入失败，请重试');
            }
            //添加记录
            $data['order_num'] = $params['id'];
            $data['buy_user_id'] = $this->userId;
            $data['sell_user_id'] = $trade['user_id'];
            $data['coin_type'] = $trade['coin_type'];
            $data['number'] = $params['number'];
            $data['price'] = $trade['price'];
            $data['status'] = 2;
            $data['pay_type'] = $trade['payment'];
            $data['create_time'] = date('Y-m-d H;i:s');
            $res2 = Db::name('otc_trade_detail')->insert($data);
            if(!$res2){
                Checking::response(-201,'插入记录失败，请重试');
            }
            //短信提醒
            $phone = Db::name('users')->where('id','=',$this->userId)->value('phone');
            $message = '您的OTC订单编号：'.$res2.'，请及时付款';
            $result = Sms::send($phone,$message);
            Checking::response(200,'订单已生成');
        }
    }

    /*
     *所有订单
     */
    public function all_order(){
        $array = Db::name('otc_trade_detail')
            ->where('buy_user_id','=',$this->userId)
            ->whereOr('sell_user_id','=',$this->userId)
            ->select();
        foreach ($array as $k=>$v){
            if($v['buy_user_id'] = $this->userId){
                $array[$k]['order_type'] = '买入';
            }else{
                $array[$k]['order_type'] = '卖出';
            }
        }
        $data['order'] = $array;
        $data['buy_time'] = Db::name('config')->where('name','=','buy_time')->value('value');
        $data['sell_time'] = Db::name('config')->where('name','=','sell_time')->value('value');
        Checking::response(200,'',$data);
    }

    /*
     * 24 otc订单
     * id  没有时查询所有买单
     */
    public function buy_order(){
        $params = input('param.');
        if(empty($params['id'])){
            $array = Db::name('otc_trade_detail')
                ->where('buy_user_id','=',$this->userId)
                ->select();
        }else{
            $array = Db::name('otc_trade_detail')
                ->where('id','=',$params['id'])
                ->select();
        }
        foreach ($array as $k=>$v){
            $array[$k]['sell_name'] = Db::name('users')->where('user_id','=',$v['sell_user_id'])->value('truename');
            $array[$k]['sell_phone'] = Db::name('users')->where('user_id','=',$v['sell_user_id'])->value('phone');
            $sellcount = Db::name('otc_trade_detail')
                ->where('sell_user_id','=',$v['sell_user_id'])
                ->where('status','=',4)
                ->count();
            $buycount = Db::name('otc_trade_detail')
                ->where('status','=',4)
                ->where('buy_user_id','=',$v['sell_user_id'])
                ->count();
            $array[$k]['finish_order'] = $sellcount + $buycount;
            //卖家收款信息
            $payment = Db::name('payment')->where('user_id','=',$v['sell_user_id'])->select();
            $yuming = 'http://'.$_SERVER['SERVER_NAME'];
            foreach ($payment as $k=>$v){
                $payment[$k]['details'] = $yuming.$v['details'];
            }
            $array[$k]['payment'] = $payment;
            $array[$k]['order_type'] = '买入';
        }
        $data['order'] = $array;
        $data['buy_time'] = Db::name('config')->where('name','=','buy_time')->value('value');
        Checking::response(200,'',$data);
    }
    /*
     *id  没有时查询所有卖单
     */
    public function sell_order(){
        $params = input('param.');
        if(empty($params['id'])){
            $array = Db::name('otc_trade_detail')
                ->where('sell_user_id','=',$this->userId)
                ->select();
        }else{
            $array = Db::name('otc_trade_detail')
                ->where('id','=',$params['id'])
                ->select();
        }
        foreach ($array as $k=>$v){
            $array[$k]['buy_name'] = Db::name('users')->where('user_id','=',$v['buy_user_id'])->value('truename');
            $array[$k]['buy_phone'] = Db::name('users')->where('user_id','=',$v['buy_user_id'])->value('phone');
            $sellcount = Db::name('otc_trade_detail')
                ->where('sell_user_id','=',$v['buy_user_id'])
                ->where('status','=',4)
                ->count();
            $buycount = Db::name('otc_trade_detail')
                ->where('status','=',4)
                ->where('buy_user_id','=',$v['buy_user_id'])
                ->count();
            $array[$k]['finish_order'] = $sellcount + $buycount;
            $array[$k]['order_type'] = '卖出';
        }
        $data['order'] = $array;
        $data['sell_time'] = Db::name('config')->where('name','=','sell_time')->value('value');
        Checking::response(200,'',$data);
    }

    /*
     * 27 未付款
     * id
     */
    public function payfinish(){
        $params = input('param.');
        if (!Checking::keyIsExistence('id', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $res = Db::name('otc_trade_detail')->where('id','=',$params['id'])->update(['status' => 3,'mate_time'=>date('Y-,-d H:i:s')]);
        if(!$res){
            Checking::response(-201,'确认付款失败，请重试');
        }
        //短信提醒
        $detail = Db::name('otc_trade_detail')->where('id','=',$params['id'])->find();
        $phone = Db::name('users')->where('id','=',$detail['sell_user_id'])->value('phone');
        $message = '您的OTC订单编号：'.$detail['id'].'，买家已经付款，请及时确认';
        $result = Sms::send($phone,$message);
        Checking::response(200,'确认付款成功');
    }

    /*
     * 放行 34
     * id
     * paypass
     */
    public function finish(){
        $params = input('param.');
        if (!Checking::keyIsExistence('id，paypass', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $user = Db::name('users')->where('id','=',$this->userId)->find();
        $trade_detail = Db::name('users')->where('id','=',$params['id'])->find();
        if($trade_detail['coin_type'] == 1){
            $coin = 'usdt';
        }else{
            $coin = 'lv';
        }
        //密码验证
        if (!Checking::checkPassword($user['pay_password'], $params['paypass'])) {
            Checking::response(-5, Checking::MESSAGE['checkPassword']);
        }
        $res1 = Db::name('otc_trade_detail')
            ->where('id','=',$params['id'])
            ->update(array('status'=>4,'pay_time'=>date('Y-m-d H:i:s')));
        if(!$res1){
            Checking::response(-201,'修改订单信息失败，请重试');
        }
        //买家加余额
        $res2 = Db::name('users_coin')
            ->where('user_id','=',$trade_detail['buy_user_id'])
            ->setInc('',$trade_detail['number']);
        if(!$res2){
            Checking::response(-201,'修改用户金额失败，请重试');
        }
        //记录
        $data['user_id'] = $trade_detail['buy_user_id'];
        $data['source_id'] = $trade_detail['sell_user_id'];
        $data['money'] = $trade_detail['number'];
        $data['balance'] = Db::name('users_coin')->where('user_id','=',$trade_detail['buy_user_id'])->value($coin);
        $data['status'] = 1;
        $data['type'] = 5;
        $data['coin_type'] = 2;
        $data['class'] = $trade_detail['coin_type'];
        $data['create_time'] = date('Y-m-d H:i:s');
        $res3 = Db::name('users_account_log')->insert($data);
        if(!$res3){
            Checking::response(-201,'添加记录失败，请重试');
        }
        Checking::response(200,'已成功放行');
    }

    /*
     * 超时处理
     */
    public function overtime(){
        //封号
        $res = Db::name('users')->where('id','=',$this->userId)->update(array('status'=>2));
        if(!$res){
            Checking::response(-201,'');
        }
        Checking::response(200,'');
    }

    /*
     * 44 发布广告
     * type 1=买入，2=卖出
     * coin_type 币种:1=USDT,2=LV
     * number
     * price
     * payment 类别:1=支付宝,2=微信,3银行卡',
     * paypass
     */
    public function trade(){
        //资格判断

        $params = input('param.');
        if (!Checking::keyIsExistence('type,coin_type,number,price,payment,paypass', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $user = Db::name('users')->where('id','=',$this->userId)->find();
        //密码验证
        if (!Checking::checkPassword($user['pay_password'], $params['paypass'])) {
            Checking::response(-5, Checking::MESSAGE['checkPassword']);
        }
        if($params['type'] == 2){//卖出
            //收款方式
            $res = Db::name('payment')
                ->where('type','=',$params['payment'])
                ->where('user_id','=',$this->userId)
                ->where('type','=',$params['payment'])
                ->where('status','=','1')
                ->find();
            if(!$res){
                Checking::response(-201,'请先完善收款方式');
            }
            //余额
            if($params['coin_type'] == 1){
                $coin = 'usdt';
            }else{
                $coin = 'lv';
            }
            $asset = Db::name('users_coin')->where('user_id','=',$this->userId)->find();
            if($asset[$coin] < $params['number']){
                Checking::response(-201,'余额不足');
            }
            //修改资金
            $res1 = Db::name('users_coin')
                ->where('user_id','=',$this->userId)
                ->setDec($coin,$params['number']);
            if(!$res1){
                Checking::response(-201,'修改余额失败，请重试');
            }
            //记录
            $data['user_id'] = $this->userId;
            $data['source_id'] = $this->userId;
            $data['money'] = $params['number'];
            $data['balance'] = Db::name('users_coin')->where('user_id','=',$this->userId['buy_user_id'])->value($coin);
            $data['status'] = 2;
            $data['type'] = 6;
            $data['coin_type'] = 2;
            $data['class'] = $params['coin_type'];
            $data['create_time'] = date('Y-m-d H:i:s');
            $res2 = Db::name('users_account_log')->insert($data);
            if(!$res2){
                Checking::response(-201,'添加资金记录失败，请重试');
            }
        }
        //生成OTC订单
        $otc['user_id'] = $this->userId;
        $otc['number'] = $params['number'];
        $otc['surplus_bumber'] = $params['number'];
        $otc['price'] = $params['price'];
        $otc['payment'] = $params['payment'];
        $otc['coin_type'] = $params['coin_type'];
        $otc['type'] = $params['type'];
        $resoult = Db::name('otc_trade')->insert($otc);
        if(!$resoult){
            Checking::response(-201,'生成订单失败，请重试');
        }
        Checking::response(200,'订单生成成功');
    }

    /*
     * 46 我的广告
     */
    public function my(){
        $data = Db::name('otc_trade')->where('user_id','=',$this->userId)->select();
        Checking::response(200,'',$data);
    }
    /*
     * 撤销
     * id
     */
    public function revoke(){
        $params = input('param.');
        if (!Checking::keyIsExistence('id', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $trade = Db::name('otc_trade')->where('id','=',$params['id'])->find();
        if($trade['surplus_bumber'] == 0){
            $res = Db::name('otc_trade')->where('id','=',$params['id'])->delete();
            if(!$res){
                Checking::response(-201,'撤销订单失败，请重试');
            }
            Checking::response(200,'撤销订单成功');
        }else{
            if($trade['coin_type'] == 1){
                $coin = 'usdt';
            }else{
                $coin = 'lv';
            }
            //金额
            $res1 = Db::name('users_coin')
                ->where('user_id','=',$this->userId)
                ->setInc($coin,$trade['surplus_bumber']);
            if(!$res1){
                Checking::response(-201,'返还金额失败，请重试');
            }
            //记录
            $data['user_id'] = $this->userId;
            $data['source_id'] = $this->userId;
            $data['money'] = $trade['surplus_bumber'];
            $data['balance'] = Db::name('users_coin')->where('user_id','=',$this->userId['buy_user_id'])->value($coin);
            $data['status'] = 1;
            $data['type'] = 14;
            $data['coin_type'] = 2;
            $data['class'] = $trade['coin_type'];
            $data['create_time'] = date('Y-m-d H:i:s');
            $res2 = Db::name('users_account_log')->insert($data);
            if(!$res2){
                Checking::response(-201,'添加资金记录失败，请重试');
            }
            //删订单
            $res3 = Db::name('otc_trade')->where('id','=',$params['id'])->delete();
            if(!$res3){
                Checking::response(-201,'撤销订单失败，请重试');
            }
            Checking::response(200,'撤销订单成功');
        }
    }
    /*
     * 申诉
     * id
     * appeal_type 申诉类型:1=买方申诉,2=卖方申诉
     * message
     */
    public function bed(){
        $params = input('param.');
        if (!Checking::keyIsExistence('id,appeal_type,message', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $res = Db::name('otc_trade_detail')
            ->where('id','=',$params['id'])
            ->update(array('appeal_type'=>$params['appeal_type'],'message'=>$params['message'],'status'=>6));
        if(!$res){
            Checking::response(-201,'申诉失败，请重试');
        }
        Checking::response(200,'申诉成功');
    }
}